package com.baizhi.aspect;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.CmfzAdminLogDao;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.entity.CmfzAdminLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class LogAop {
    @Autowired
    private CmfzAdminLogDao cmfzAdminLogDao;

    /**
     * 切点
     * 切方法
     * 切注解 更加灵活
     */
    @Pointcut("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void logPoint(){}

    /**
     * 日志增强
     */
    @After("logPoint()")
    public void logAfter(JoinPoint joinPoint){
        /**
         * 获取日志数据
         */
        CmfzAdminLog cmfzAdminLog = new CmfzAdminLog();
//        获取时间
        cmfzAdminLog.setLogDate(new Date());

//        获取admin的id 从session
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        获取request
        HttpServletRequest request = requestAttributes.getRequest();
//        通过request获取session
        HttpSession session = request.getSession();

//        CmfzAdmin admin = (CmfzAdmin) session.getAttribute("admin");

        cmfzAdminLog.setAdminId(1);

//        获取ip
        cmfzAdminLog.setLogIp(IPKit.getIpAddrByRequest(request));

        /**
         * LogContent
         * 执行了一个查询上师的方法 content内容应该是：查询上师
         * 执行了一个删除上师的方法 content内容应该是：删除上师
         *
         * 执行的方法不同 内容和type都不一样
         *
         * 自定义注解
         */
//        获取注解的值
//        1.获取方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        2.获取方法对象
        Method method = signature.getMethod();
//        3.获取方法上的注解
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
//        4.获取注解的值
        cmfzAdminLog.setLogContent(annotation.content());
        cmfzAdminLog.setLogType(annotation.type());
        /**
         * 添加数据库
         */
        cmfzAdminLogDao.insert(cmfzAdminLog);
    }

}
